import { Component, inject, OnInit } from '@angular/core';
import { DelonFormModule, SFSchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { NzSpinModule } from 'ng-zorro-antd/spin';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';
import { PublicService } from 'src/app/shared/service/public.service';

@Component({
  selector: 'aapp-system-resource-group',
  templateUrl: './resource-group.component.html',
  imports: [NzSpinModule, DelonFormModule, NzButtonModule]
})
export class ResourceGroupComponent implements OnInit {
  record: NzSafeAny = {};
  schema: SFSchema = {};
  parentId = '0';

  protected readonly http = inject(_HttpClient);
  private readonly msgSrv = inject(NzMessageService);

  protected readonly modal = inject(NzModalRef);
  protected readonly pubService = inject(PublicService);

  ngOnInit(): void {
    this.initSchema();
  }

  initSchema() {
    this.schema = {
      properties: {
        name: { type: 'string', title: '组名称', maxLength: 25, ui: { spanLabel: 5, spanControl: 19, grid: { span: 24 } } },
        remark: { type: 'string', title: '备注', maxLength: 25 }
      },
      required: ['name']
    };
  }

  save(value: NzSafeAny) {
    if (this.record.id) {
      value.id = this.record.id;
      this.http.put(`${Api.BaseResourceApi}/group`, value).subscribe((res: NzSafeAny) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('修改成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('修改失败，未知错误');
        }
      });
    } else {
      value.parentId = this.parentId;
      this.http.post(`${Api.BaseResourceApi}/group`, value).subscribe((res: NzSafeAny) => {
        if (res) {
          if (res.code === ResponseCode.SUCCESS) {
            this.msgSrv.success('保存成功');
            this.modal.close(true);
          } else {
            this.msgSrv.warning(res.message);
          }
        } else {
          this.msgSrv.error('保存失败，未知错误');
        }
      });
    }
  }

  close() {
    this.modal.destroy();
  }
}
